package com.example.lock;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

/**
 * Create with Intellij idea
 * User:mingtian
 * Date:2018/10/22
 * Time:9:02
 */
public class ZookeeperDistrbuteLock extends ZookeeperAbstractLock {

    //获取锁
    @Override
    boolean tryLock() {
        try {
            //创建临时节点
            zkClient.createEphemeral(lockPath);
            return true;
        } catch (Exception e) {
            //如果创建该节点失败 这个时候直接走catch
            return false;
        }
    }


    @Override
    void waitLock() {

        IZkDataListener iZkDataListener = new IZkDataListener() {
            //节点发生改变
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }

            //节点被删除
            @Override
            public void handleDataDeleted(String s) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();//计数器一旦为0 后面不在执行
                }
            }
        };

        //监听事件通知
        zkClient.subscribeDataChanges(lockPath, iZkDataListener);

        //如何控制程序等待
        if (zkClient.exists(lockPath)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();//进行等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //后面代码继续执行
        //为了不影响程序的效率，建议删除改事件监听
        zkClient.unsubscribeDataChanges(lockPath, iZkDataListener);
    }


}
